package com.tian.jobhandler;

import com.tian.client.ChargeRecordClient;
import com.tian.common.CommonResult;
import com.tian.dto.ChargeTimesCountRespDto;
import com.tian.enums.ResultCode;
import com.tian.util.DateUtils;
import com.tian.util.RedisConstantPre;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import static com.xxl.job.core.biz.model.ReturnT.SUCCESS;

/**
 * {@code @description:} 每月数据统计（上个月累计充电次数、累计充电电量、累计支付单单数量、累计支付金额）
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024-03-23 11:42
 * {@code @version:} 1.0
 */
@Slf4j
@Component
public class MonthCountStatisticsJob {

    @Resource
    private ChargeRecordClient chargeRecordClient;
    @Resource
    private RedissonClient redissonClient;

    @XxlJob("monthCountStatisticsJobHandler")
    public void process() {
        log.info("开始执行 monthCountStatisticsJobHandler 定时任务");
        XxlJobHelper.log("start monthCountStatisticsJobHandler job");
        Date date = new Date();
        String lastMonth = DateUtils.formatDateTime(DateUtils.add(date, Calendar.DAY_OF_MONTH, -1));
        CommonResult<ChargeTimesCountRespDto> chargetimescountrespdtocommonresult = chargeRecordClient.chargeTimesCount(lastMonth);
        if (chargetimescountrespdtocommonresult.getCode() == ResultCode.SUCCESS.getCode()) {
            ChargeTimesCountRespDto chargeTimesCountRespDto = chargetimescountrespdtocommonresult.getData();
            //存入redis缓存中，下次读取直接从redis中读取即可
            RBucket<Integer> bucket = redissonClient.getBucket(RedisConstantPre.MONTH_COUNT_STATISTICS_CHARGE + date);
            bucket.set(chargeTimesCountRespDto.getCount());
            log.info("充电次数已添加到缓存，date={},次数={}", date, chargeTimesCountRespDto.getCount());
            XxlJobHelper.log("充电次数已添加到缓存，date={},次数={}", date, chargeTimesCountRespDto.getCount());
        }
    }
}
